package com.xj.util;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

/**
 * @version 1.0
 * @program: demo2
 * @packageName: com.xj.util
 * @className JedisUtil
 * @description: TODO
 * @author: xj
 * @create: 2021-01-08 16:54:05
 **/
@Service
public class JedisUtil {

    @Autowired
    private JedisPool jedisPool;

    private static final String KEY="lock";
    private static final String VALUE="TRUE";
    private static final int  EXPIRE=5; //秒

    public boolean tryExpireLock() {
        Jedis jedis = null;
        try {
            jedis = jedisPool.getResource();

            if(jedis.setnx(KEY,VALUE)==1){
                jedis.expire(KEY,EXPIRE);
                return true;
            }

        } catch (Exception e) {
            e.printStackTrace();
            return false;
        } finally {
            if (jedis != null) {
                jedis.close();
            }
        }
        return false;
    }

    public String set(String key, String value) {
        Jedis jedis = null;
        String result = null;
        try {
            jedis = jedisPool.getResource();
            result = jedis.set(key,value);
        } catch (Exception e) {
            e.printStackTrace();
            return result;
        } finally {
            if (jedis != null) {
                jedis.close();
            }
        }
        return result;
    }

    public String get(String key) {
        Jedis jedis = null;
        String result = null;
        try {
            jedis = jedisPool.getResource();
            result = jedis.get(key);
        } catch (Exception e) {
            e.printStackTrace();
            return result;
        } finally {
            if (jedis != null) {
                jedis.close();
            }
        }
        return result;
    }
}
